﻿using MxWeiXinPF.BLL;
using MxWeiXinPF.Common;
using MxWeiXinPF.Model;
using MxWeiXinPF.WeiXinComm;
using Senparc.Weixin;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.AdvancedAPIs.User;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Helpers;
using Senparc.Weixin.MP.TenPayLibV3;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;

//1e2124dd04e11d01b9df2865f85944be
namespace MxWeiXinPF.Web.UI
{
    /// <summary>
    /// 前端微信第3方页面的父级页面
    /// author:李　朴
    /// datetime:2015-8-8
    /// update:2015-9-25
    /// </summary>
    public class WeiXinPage : System.Web.UI.Page
    {
        //分享js的参数
        public FxModel fxModel = new FxModel();

        // private  string _openid;

        public string openid
        {
            get
            {

                if (HttpContext.Current.Session["openid"] != null && HttpContext.Current.Session["openid"].ToString().Trim() != "")
                {
                    return HttpContext.Current.Session["openid"].ToString();
                }
                else
                {
                    return "";
                }

            }
            set
            {

                HttpContext.Current.Session["openid"] = value;
            }

        }

        public bool isGuanZhu = false;//是否关注了
     
        public string mywebSite = MyCommFun.getWebSite();
        /// <summary>
        /// 只允许微信里访问
        /// </summary>
        /// <param name="flg"></param>
        public void OnlyWeiXinLook()
        {

            string value = BLL.wx_sysConfig.GetConfigValue("onlyweixinlook");
            if (value.ToLower() == "true")
            {
                String userAgent = Request.UserAgent;
                if (userAgent.IndexOf("MicroMessenger") <= -1)
                {
                    Response.Write("请在微信浏览器里访问");
                    Response.End();
                }
            }

        }

        public Model.wxcodeconfig getwebsiteinfo(int wid)
        {
            wsiteBll wBll = new wsiteBll();
            return wBll.GetModelByWid(wid, "");
        }

        /// <summary>
        /// 获得版权信息
        /// </summary>
        /// <param name="wid"></param>
        /// <returns></returns>
        public string getwebcopyright(int wid)
        {
            wsiteBll wBll = new wsiteBll();
            Model.wxcodeconfig config = wBll.GetModelByWid(wid, "");
            if (config != null)
            {
                return config.wcopyright;
            }
            else
            {
                return "";
            }


        }


        protected void OAuth2BaseProc(int wid, string thisUrl)
        {
            //授权
            BLL.wx_userweixin bll = new BLL.wx_userweixin();
            Model.wx_userweixin uWeiXinModel = bll.GetModel(wid);
            OAuth2BaseProc(uWeiXinModel, "index", thisUrl);
            //授权 end

        }


        /// <summary>
        /// 授权判断，页面跳转
        /// </summary>
        /// <param name="state"></param>
        /// <param name="targetUrl">目标地址</param>
        public void OAuth2BaseProc(Model.wx_userweixin model, string state, string targetUrl)
        {

            BLL.wx_property_info propertyBll = new BLL.wx_property_info();
            Model.wx_property_info propertyEntity = propertyBll.GetModelByIName(model.id, MXEnums.WXPropertyKeyName.OpenOauth.ToString());

            if (Page.Session["isGuanZhu"] != null && (bool)Page.Session["isGuanZhu"])
            {
                isGuanZhu = (bool)Page.Session["isGuanZhu"];
            }
            if (openid != null && openid != "")
            {
                return;
            }


            if (propertyEntity == null || propertyEntity.iContent == "0")
            {
                //关闭了网页授权
                openid = MyCommFun.RequestOpenid();
            }
            else
            {
                string code = MyCommFun.QueryString("code");
                if (code == null || code.Trim() == "")
                {
                    if (targetUrl == null || targetUrl.Trim() == "")
                    {
                        targetUrl = MyCommFun.getTotalUrl();
                    }
                    string newUrl = OAuthApi.GetAuthorizeUrl(model.AppId, targetUrl, state, OAuthScope.snsapi_base);
                    WXLogs.AddLog("处理请求Oauth2.0", "网页授权跳转之前", "OAuth2BaseProc 跳转之前newUrl=" + newUrl, 1);
                    Response.Redirect(newUrl);
                }
                else
                {

                    var result = OAuthApi.GetAccessToken(model.AppId, model.AppSecret, code);

                    if (result.errcode != ReturnCode.请求成功)
                    {
                        WXLogs.AddLog("处理请求Oauth2.0", "WeiXinPage OAuth2BaseProc  请求失败", "错误= " + result.errmsg, 1);
                        openid = "";
                        return;
                    }
                    openid = result.openid;
                }

               

                //判断用户是否关注了  ---start
                UserInfoJson userInfo = null;
                try
                {
                    string err = "";
                    string accessToken = WeiXinCRMComm.getAccessToken(model.id, out err);

                    userInfo = UserApi.Info(accessToken, openid);
                    if (userInfo != null && userInfo.subscribe == 1)
                    {
                        isGuanZhu = true;
                        //WXLogs.AddLog("【微投票】", "WeiXinPage OAuth2BaseProc  用户关注了", "openid= " + openid, 1);
                    }
                    else
                    {
                        // WXLogs.AddLog("【微投票】", "WeiXinPage OAuth2BaseProc  用户未关注", "openid= " + openid, 1);
                        isGuanZhu = false;
                    }

                    Page.Session["isGuanZhu"] = isGuanZhu;

                }
                catch (ErrorJsonResultException ex)
                {
                    //未关注，只能授权，无法得到详细信息
                    isGuanZhu = false;
                    // WXLogs.AddLog("【微投票】", "WeiXinPage OAuth2BaseProc  用户未关注", " openid=" + openid + ", ex: " + ex.Message, 1);
                }
                //判断用户是否关注了  ---start


            }
           
        }



        #region 分享的jssdk代码

        /// <summary>
        /// jssdk初始化
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="fxUrl"></param>
        public void jssdkInit(int wid, string fxUrl = "")
        {

            BLL.wx_userweixin bll = new BLL.wx_userweixin();
            Model.wx_userweixin uWeiXinModel = bll.GetModel(wid);
            jssdkInit(uWeiXinModel, fxUrl);
        }
        /// <summary>
        /// 若不管用，请在公众号官方后台---功能设置----js接口安全域名 设置
        ///    初始化微信分享
        /// </summary>
        /// <param name="wxModel"></param>
        /// <param name="fxUrl">分享的目标url，如果传过来的值为空字符串或者为null则默认是当前的网址</param>
        public void jssdkInit(Model.wx_userweixin wxModel, string fxUrl = "")
        {
            BLL.wx_property_info propertyBll = new BLL.wx_property_info();
            //Model.wx_property_info propertyEntity = propertyBll.GetModelByIName(wxModel.id, MXEnums.WXPropertyKeyName.OpenOauth.ToString());
            //if (propertyEntity.iContent == "0")
            //{
            //    return;
            //}

            fxModel.appid = wxModel.AppId;
            fxModel.timestamp = JSSDKHelper.GetTimestamp();
            fxModel.nonce = JSSDKHelper.GetNoncestr();
            fxModel.thisUrl = HttpContext.Current.Request.Url.ToString();

            if (fxUrl == null || fxUrl.Trim() == "")
            {
                fxModel.fxUrl = fxModel.thisUrl;
            }
            else
            {
                fxModel.fxUrl = fxUrl;
            }

            if (string.IsNullOrEmpty(fxModel.fxImg)) fxModel.fxImg = "";
            if (string.IsNullOrEmpty(fxModel.fxTitle)) fxModel.fxTitle = "";
            if (string.IsNullOrEmpty(fxModel.fxContent)) fxModel.fxContent = "";

            string error = "";
            string ticket = MxWeiXinPF.WeiXinComm.WeiXinCRMComm.getJsApiTicket(wxModel.id, out  error);
            if (error != "")
            {  //取临时票据出现问题

                return;
            }

            //获取签名
            var signature = JSSDKHelper.GetSignature(ticket, fxModel.nonce, fxModel.timestamp, fxModel.thisUrl);

            fxModel.signature = signature;
        }//end:function
        //SHA1哈希加密算法  
        public string SHA1_Hash(string str_sha1_in)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str_sha1_in);
            byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
            string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
            str_sha1_out = str_sha1_out.Replace("-", "").ToLower();
            return str_sha1_out;
        }


        #endregion


    }
}
